1
|
|
|
/** |
2
|
|
|
* Common Service API router |
3
|
|
|
* |
4
|
|
|
* @since 1.0.0 |
5
|
|
|
*/ |
6
|
|
|
|
7
|
4 |
|
const Joi = require('joi'); |
8
|
4 |
|
const User = require('./../repository/User'); |
9
|
4 |
|
const config = require('../config/server.config').url; |
10
|
4 |
|
const util = require('../common/common-util'); |
11
|
4 |
|
const authUtil = require('../common/auth-util'); |
12
|
4 |
|
const NotifierError = require('../common/Error'); |
13
|
4 |
|
const logger = require('winston'); |
14
|
|
|
|
15
|
4 |
|
module.exports = [ |
16
|
|
|
{ |
17
|
|
|
method: 'POST', |
18
|
|
|
path: `${config.apiPrefix}/login`, |
19
|
|
|
handler: (request, reply) => { |
20
|
2 |
|
const clientIP = util.getClientIp(request); |
21
|
2 |
|
if (process.env.ALLOWED_IP && !process.env.ALLOWED_IP.includes(clientIP)) { |
22
|
|
|
logger.warn(`[Auth] This client IP is not allowed.: ${clientIP}`); |
23
|
|
|
return reply(new NotifierError(NotifierError.Types.FORBIDDEN_IP_ADDRESS, { remoteAddress: clientIP })); |
24
|
|
|
} |
25
|
2 |
|
if (!request.payload.username || !request.payload.password) { |
26
|
|
|
return reply(new NotifierError(NotifierError.Types.AUTH_MISSING_PARAMS)); |
27
|
|
|
} |
28
|
2 |
|
return User.find({ username: request.payload.username }).then((account) => { |
29
|
2 |
|
if (!account || account.length === 0 || !authUtil.comparePassword(request.payload, account[0].password)) { |
30
|
1 |
|
return reply(new NotifierError(NotifierError.Types.AUTH_INVALID_PARAMS)); |
31
|
|
|
} |
32
|
1 |
|
const token = authUtil.generateToken(Object.assign({}, account[0], { ip: clientIP })); |
33
|
1 |
|
return reply().state('token', token); |
34
|
|
|
}); |
35
|
|
|
}, |
36
|
|
|
config: { |
37
|
|
|
auth: false, |
38
|
|
|
}, |
39
|
|
|
}, |
40
|
|
|
{ |
41
|
|
|
method: 'PUT', |
42
|
|
|
path: `${config.apiPrefix}/passwords`, |
43
|
1 |
|
handler: (request, reply) => User.updatePassword(request.auth.credentials.username, request.payload.password) |
44
|
1 |
|
.then(result => reply(result)) |
45
|
|
|
.catch(err => reply(err)), |
46
|
|
|
config: { |
47
|
|
|
validate: { |
48
|
|
|
payload: { |
49
|
|
|
password: Joi.string().min(8).required(), |
50
|
|
|
}, |
51
|
|
|
}, |
52
|
|
|
}, |
53
|
|
|
}, |
54
|
|
|
]; |
55
|
|
|
|